package com.wpam.scrabble.mobile.communication;

import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.wpam.scrabble.mobile.messages.Message;

public class MsgBuffer {
	final private Lock lock = new ReentrantLock();
	final private Condition notEmpty = lock.newCondition();
	private boolean running_ = false;
	
	final private ArrayList<Message> items = new ArrayList<Message>();

	public void start() {
		this.running_ = true;
	}
	
	public void put(Message msg) {
		
		lock.lock();
		items.add(msg);
		notEmpty.signal();
		lock.unlock();
	}
	
	public Message take() {
		
		Message retMsg = null;
		lock.lock();
		try {
			while (running_ && items.size() == 0) { 
				notEmpty.await();
				if (!running_)
					return null;
			}
			retMsg = items.remove(0);
		} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
		} finally {
				lock.unlock();
		}
		return retMsg;
	}
	
	public void endWork() {
		
		running_ = false;
		lock.lock();
		notEmpty.signal();
		items.clear();
		lock.unlock();
	}
}
